<?php
declare (strict_types = 1);
namespace app\api\logic;
use app\admin\model\User as userModel;
use app\admin\model\UserMoneyLog as um;
use app\admin\model\UserScoreLog as us;
use app\common\model\Address;
use app\admin\model\Config as configModel;
use app\common\Token;
use app\api\validate\Address as AddressValidate;
class UserLogic
{		
	//微信授权登录
	function wxLogin($args = []){
			 $add = userModel::where("id",3)->find()->toArray();
			 $aid = $add['id'];
			 $openid = $add['wx_openid'];
	         $token = Token::createToken(['uid'=>$aid,'wx_openid'=>$openid,'nickname'=>$add['nickname']]);
	         return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>['token'=>$token,'userinfo'=>$add]];


			$cs = configModel::getShopSettings($args['shop_id']); //获取店铺相关配置
			$appid = $cs['xcx_appid'];
	        $appsercert =  $cs['xcx_appsercert'];
	        if($appid && $appsercert){
	            $code =  $args['code'] ?? '';
	            $yaoid = $args['yaoid'] ?? 0;
	            if($code == ''){
	            	 return ['code'=>100,'back_type'=>1,'msg'=>'code不存在'];
	            }

	            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $appsercert . "&js_code=" . $code . "&grant_type=authorization_code";
	            $arr = vget($url); // 一个使用curl实现的get方法请求
	            $arr = json_decode($arr, true);
	            if (!isset($arr['openid'])) {
	                   return ['code'=>100,'back_type'=>1,'msg'=>'授权失败，请重试'];
	            }
	            $openid = $arr['openid'];

	           
	            $ip = $args['ip'];
	            $w = array();
	            $w['wx_openid'] = $openid;
	            $user = userModel::where($w)->find();
	            if($user){
	                userModel::where($w)->update(['last_login_time'=>time(),'last_login_ip'=>$ip,'update_time'=>time()]);
	                $token = Token::createToken(['uid'=>$user['id'],'wx_openid'=>$openid,'nickname'=>$user['nickname']]);
	                return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>['token'=>$token,'userinfo'=>$user]]; 
	            }else{
	                $add = array();
	                $add['nickname'] = "用户" . createRandomStr(6);
	                $add['create_time'] = time();
	                $add['update_time'] = time();
	                $add['last_login_ip'] = $ip;
	                $add['wx_openid'] = $openid;
	                $add['yao_id'] = $yaoid;
	                $add['shop_id'] = $args['shop_id'];
	                $aid = userModel::insertGetId($add);
	                if($aid){
	                     $add['id'] = $aid;
	                     $token = Token::createToken(['uid'=>$aid,'wx_openid'=>$openid,'nickname'=>$add['nickname']]);
	                     return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>['token'=>$token,'userinfo'=>$add]];
	                }
	            }
	        }else{
	             return ['code'=>100,'back_type'=>1,'msg'=>'暂无法登录'];
	        }
	}



    //获取用户基本信息
    function userInfo($args = []){
           $user = userModel::where("id",$args['uid'])->find();
           return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>$user];
    }

     //更新用户信息
    function updateUserInfo($args = []){
    	if(isset($args['nickname'])){
    		 $data['nickname'] = $args['nickname'];
    	}
    	if(isset($args['username'])){
    		 $data['username'] = $args['username'];
    	}
    	if(isset($args['avatar'])){
    		 $data['avatar'] = $args['avatar'];
    	}
	    $user = userModel::where("id",$args['uid'])->update($data);
	    if($user){
	    	 return ['code'=>200,'back_type'=>1,'msg'=>'ok'];
	    }else{
	    	 return ['code'=>100,'back_type'=>1,'msg'=>'无任何更新'];
	    }
	    
    }

    //微信授权获取手机号
    function getPhoneByWx($args = []){
	        header("Content-Type:text/html;charset=utf8");
            header("Access-Control-Allow-Origin: *"); //解决跨域
            header('Access-Control-Allow-Methods:POST'); // 响应类型
            header('Access-Control-Allow-Headers:*'); // 响应头设置
            $appid = tconfig::getConfig("xcx_appid");
            $appsercert = tconfig::getConfig("xcx_appsercert");
            $uid = $this->request->uid;
            $code = input("post.code");
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsercert . '&js_code=' . $code . '&grant_type=authorization_code';
            $rest = vget($url);
            if ($rest) {
                $str = stripslashes($rest);
                $arr = json_decode($str, true);
                $session_key = $arr['session_key'];
                //开发者如需要获取敏感数据，需要对接口返回的加密数据( encryptedData )进行对称解密
                import('Wxbiz.wxBizDataCrypt', EXTEND_PATH);
                $encryptedData = urldecode(input("post.encryptedData"));
                $iv = input("post.iv");
                $iv = str_replace(" ", "+", $iv);
                $pc = new \WXBizDataCrypt($APPID, $session_key);
                $errCode = $pc->decryptData($encryptedData, $iv, $data); //其中$data包含用户的所有数据
                if ($errCode != 0) {
                     return json(['code'=>100,'msg'=>'授权失败，请重试！']);
                }
                $res = json_decode($data, true);
                if(intval($res['purePhoneNumber']) > 0){
                    $re = userModel::where(array('uid' => $uid))->update(array('phone' => intval($res['purePhoneNumber'])));
                    if ($re) {
                          return json(['code'=>200,'msg'=>'ok']);
                    }else {
                         return json(['code'=>100,'msg'=>'手机号更新失败']);
                    }
                }else{
                    return json(['code'=>100,'msg'=>'获取手机号为空']);
                }
            }else{
                 return json(['code'=>100,'msg'=>'授权失败']);
            }
    }

    //用户余额记录
    function userBalance($args = []){
    	  $res = um::where("user_id",$args['uid'])->order("id desc")->select();
    	  return $res;
    }

    //用户积分记录
    function userIntegral($args = []){
    	  $res = us::where("user_id",$args['uid'])->order("id desc")->select();
    	  $score = userModel::where("id",$args['uid'])->value("score");

    	  return ['data'=>['lists'=>$res,'user_score'=>$score]];
    }
    //用户收货地址
    function userAddress($args = []){
	  	 $res = Address::where("user_id",$args['uid'])->order("default desc")->select();
	     return $res;
    }
    //删除用户收货地址
    function userAddressDel($args = []){
    	 if(!isset($args['id']) || $args['id'] == 0){
    	 	 return ['code'=>100,'back_type'=>1,'msg'=>'删除失败'];
    	 }
	  	 $res = Address::where(['user_id'=>$args['uid'],'id'=>$args['id']])->delete();
	  	 if($res){
	  	 		return ['code'=>200,'back_type'=>1,'msg'=>'ok'];
	  	 }else{
	  	 		return ['code'=>100,'back_type'=>1,'msg'=>'删除失败！'];
	  	 }
	    
    }
    //收货地址详细
    function userAddressDetail($args = []) 
    {
    	 if(!isset($args['id']) || $args['id'] == 0){
    	 	 return ['code'=>100,'back_type'=>1,'msg'=>'no data'];
    	 }
	  	 $res = Address::where(['user_id'=>$args['uid'],'id'=>$args['id']])->find();
	  	 if($res['area']){
	  	 	 $res['area'] = explode(",",$res['area']);
	  	 }
	  	 return $res;
    }

     //用户默认收货地址
    function userDefaultAddress($args = []){
	  	 $res = Address::where(['user_id'=>$args['uid'],'default'=>1])->find();
	     return $res;
    }

    // 用户地址新增和更新
    function subAddress($args = []){
    	   $data = [];
    	   $act = isset($args['act']) ?? '';
    	   switch ($act) {
    	   	case 'SETMO':  //设置某个地址为默认地址
    	   	    $aid = $args['aid'];
    	   	    if($aid){
    	   	         Address::where(['user_id'=>$args['uid']])->update(['default'=>0]);	
    	   	    	 Address::where(['user_id'=>$args['uid'],'id'=>$aid])->update(['default'=>1]);
    	   	    	 return ['code'=>200,'back_type'=>1,'msg'=>'ok'];
    	   	    }else{
    	   	    	return ['code'=>100,'back_type'=>1,'msg'=>'设置失败'];
    	   	    }
    	   		break;
    	   	
    	   	default:
    	   		   if(isset($args['data'])){
	    	   		   $jsonString = str_replace('&quot;', '"', $args['data']);
	    	   		   $data = json_decode($jsonString,true);
		    	   }else{
		    	   		   $data['uname'] = $args['uname']??'';
				    	   $data['phone'] = $args['phone']??'';
				    	   $data['address'] = $args['address'] ?? '';
				    	   
		    	   }
		    	    $data['area'] = $args['area'] ?? '';
		    	    $data['user_id'] = $args['uid'];
		    	    $validate = new AddressValidate();
			        if(!$validate->scene('add')->check($data)){
			        	  return ['code'=>100,'back_type'=>1,'msg'=>$validate->getError()];
			        }
			        $find = Address::where("user_id",$args['uid'])->find();
			        if(empty($find)){
			        	  $data['default'] = 1;
			        }else{
			        	  if(isset($args['mo'])){
			        	  	    Address::where("user_id",$args['uid'])->update(['default'=>0]);
			        	  	    $data['default'] = 1;
			        	  }
			        }
			        if(isset($args['aid'])){
			        	 $aid = Address::where(['user_id'=>$args['uid'],'id'=>$args['aid']])->update($data);
			        }else{
			        	 $aid = Address::insertGetId($data);
			        }
				    
				    if($aid){
				   	   return ['code'=>200,'back_type'=>1,'msg'=>'ok'];
				    }else{
				   	   return ['code'=>100,'back_type'=>1,'msg'=>'保存失败'];
				    }

    	   		break;
    	   }
    	    

    }

}